import {messages} from "share/common";
import React from 'react'
import {connect} from 'react-redux'
import { Button, message, Modal, Popover } from 'antd';
import SlideFrame from 'components/slide-frame';
import ResizeTable from 'components/resize-table'
import HeaderRule from "containers/financial-account/doc-template/header-rule";
import docTemplateService from "containers/financial-account/doc-template/doc-template-service";
import ImportModal from "components/template/import-modal-ie/import-modal";
import 'styles/setting/wait-for-billing/invoice-status-query.scss';
import AsyncExport from "components/template/async-export/async-export";

class templateHeader extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      setOfBooksId: this.props.company.setOfBooksId,
      columns: [
        { title: messages('common.sequence')/*序号*/, dataIndex: 'sequence' },
        {title: messages('financial-account.key16')/*凭证明细编码*/, dataIndex: 'ledgerCode', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key17')/*凭证明细名称*/, dataIndex: 'ledgerName', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key151')/*接口编码*/, dataIndex: 'interfaceCode', render: value => <Popover content={value} placement={'topLeft'}>{value}</Popover>},
        {title: messages('financial-account.key18')/*凭证组合因素*/, width: 120, dataIndex: 'isCombination', render:(value) => value ? 'Y' : 'N'},
        {title: messages('financial-account.key19')/*必输字段（视接口）*/, width: 160, dataIndex: 'isNotEmpty', render:(value) => value ? 'Y' : 'N'},
        {title: messages('financial-account.key20')/*固化字段标志*/, dataIndex: 'curingFieldName'},
        {title: messages('financial-account.key165')/*规则字段标志*/, dataIndex: 'ruleDefine', render: value => (value && value.ruleName) ? value.ruleName : ''},
        {title: messages('common.operation')/*操作*/, width: 150, dataIndex: 'operation', render: (value,record) => {
            return (
              <span>
                <a onClick={e => this.handleEdit(e,record)}>{messages('common.edit')/*编辑*/}</a>
                <span className="ant-divider"/>
                <a onClick={() => Modal.confirm({
                  title: messages('financial-account.key196')/*确认删除*/,
                  content: messages('financial-account.key197')/*删除后，不修改已生成的分录，但可能会导致原分录的此字段无法查询。*/,
                  onOk: () => this.handleDelete(record)
                })}>{messages('common.delete')/*删除*/}</a>
              </span>
            )
          }},
      ],
      data: [],
      loading: false,
      pagination: {
        total: 0
      },
      page: 0,
      showSlideFrame: false,
      title: '',
      editRecord: {},
    }
  }

  componentWillMount() {
    this.setState({setOfBooksId: this.props.setOfBooksId}, () => {
      this.getList();
    })
  }

  componentWillReceiveProps(nextProps) {
    this.setState({setOfBooksId: nextProps.setOfBooksId},() => {
      this.getList();
    })
  }

  getList = () => {
    const { setOfBooksId, page } = this.state;
    let temp = {
      page,
      lineType: 1001
    };
    this.setState({loading: true});
    docTemplateService.getTemplateList(setOfBooksId,temp).then(res => {
      this.setState({
        loading: false,
        data: res.data.rows,
        pagination: {
          total: Number(res.data.total),
          current: page + 1,
          onChange: this.onChangePager,
        }
      });
    }).catch(e => {
      message.error(e.response.data.message);
      this.setState({loading: false})
    })
  };

  onChangePager = (page) => {
    if (page - 1 !== this.state.page)
      this.setState({
        page: page - 1
      }, () => {
        this.getList();
      })
  };

  handleEdit = (e,record) => {
    e.stopPropagation();
    this.setState({
      title: messages('financial-account.key21')/*编辑凭证头明细*/,
      editRecord: record
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  handleAdd = () => {
    this.setState({
      title: messages('financial-account.key22')/*新建凭证头明细*/,
      editRecord: {}
    },() => {
      this.setState({showSlideFrame: true});
    })
  };

  isRefresh = isRefresh => {
    this.setState({showSlideFrame: false});
    isRefresh === true && this.getList();
  };

  handleDelete = record => {
    docTemplateService.validateDelete(record.id).then(res => {
      if (res.data.checkPass) {
        docTemplateService.deleteJournal(record.id).then(() => {
          this.getList();
        })
      } else {
        Modal.error({
          title: messages('financial-account.key198')/*删除失败*/,
          content: (<div>
            {res.data.warningList.map(item => <div>{item.errorMsg}</div>)}
          </div>)
        })
      }
    }).catch(e => {
      message.error(e.response.data.message);
    });
  };

  render(){
    const { columns, data, loading, pagination, title, editRecord, showSlideFrame, setOfBooksId } = this.state;
    const { language, loginUser } = this.props;
    return(
      <div className="invoice-status">
        <div style={{marginBottom:'10px'}} className="buttons">
          <Button type='primary' onClick={this.handleAdd}>{messages('common.create')/*新建*/}</Button>
          <ImportModal
            buttonName={messages('financial-account.key163')/*导入数据*/}
            templates={[{
              downloadName: messages('financial-account.key199')/*凭证模板头模版*/,
              templateName: messages('financial-account.key199')/*凭证模板头模版*/,
              downloadUrl: `/ledger/api/download/template`,
              downloading: "headerLoading",
              downloadMethod: 'post',
              params: {
                templateType: 'JOURNAL_TEMPLATE',
                language: language.code,
                otherDownLoadMsg: {
                  setOfBooksId: setOfBooksId,
                  type: "HEAD"
                }
              }
            }]}
            hasErrInfo={false}
            uploadAsync
            listenUrl={'/ledger/api/transaction/log/query/by'}
            exportErrUrl={'/ledger/api/transaction/log/export/errorMsg/${transactionOID}' + `?language=${language.code}`}
            uploadUrl={`/ledger/api/journal/line/define/config/import?type=HEAD&setOfBooksId=${setOfBooksId}&operatorOid=${loginUser.userOID}&tenantId=${loginUser.tenantId}`}
            onCancel={() => {
              this.setState({page: 0}, () => {
                this.getList();
              })
            }}
          />
          <div style={{display:'inline-block'}}>
            <AsyncExport
              title={messages('financial-account.key164')/*导出数据*/}
              style={{ display: 'inline-block' }}
              params={{
                tenantId: loginUser.tenantId,
                setOfBooksId: setOfBooksId,
                operatorOid: loginUser.userOID,
                implName: 'JLDDownloadServiceImpl',
                language: language.code,
                isAsync: true,
                otherDownloadMsg: {
                  type: "HEAD"
                }
              }}
            />
          </div>
        </div>
        <ResizeTable
          columns={columns}
          dataSource={data}
          loading={loading}
          rowKey={'id'}
          pagination={pagination}
          bordered
        />
        <SlideFrame show={showSlideFrame}
                    title={title}
                    params={{
                      showSlideFrame,
                      editRecord,
                      setOfBooksId
                    }}
                    content={HeaderRule}
                    onClose={(isRefresh) => this.isRefresh(isRefresh)}
                    afterClose={(isRefresh) => this.isRefresh(isRefresh)}/>
      </div>
    )
  }
}

function mapStateToProps(state){
  return {
    company: state.login.company,
    loginUser: state.login.loginUser,
    language: state.main.language
  }
}

export default connect(mapStateToProps)(templateHeader);
